/*
 * @Author: minglic minglic@foxmail.com
 * @Date: 2023-10-21 09:20:45
 * @LastEditors: minglic minglic@foxmail.com
 * @LastEditTime: 2023-10-21 11:28:51
 * @FilePath: \go2023\admin\internal\service\impl\site.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package impl

import (
	"sxk.games/m/v2/core/entity"
	"sxk.games/m/v2/core/utils"
	"sxk.games/m/v2/core/utils/data"
)

type Site struct{}

func (*Site) Create(site *entity.Site) (any, error) {
	site.Id = utils.GetUUID()
	err := data.GetDb().Create(site).Error
	return nil, err
}

func (*Site) Delete(id string) (any, error) {
	err := data.GetDb().Model(&entity.Site{}).Where("id = ?", id).Delete(nil).Error
	return nil, err
}

func (*Site) Update(site *entity.Site) (any, error) {

	//1、通过ID查询数据库中旧的数据

	var siteDb entity.Site
	err := data.GetDb().Model(&siteDb).Where("id = ?", site.Id).Find(&siteDb).Error
	if err != nil {
		return nil, err
	}

	//2、将客户端上传的数据替换进去

	siteDb.Name = site.Name
	siteDb.Address = site.Address
	siteDb.Desc = site.Desc
	siteDb.Manager = site.Manager

	//3、保存
	err = data.GetDb().Save(siteDb).Error
	return nil, err
}

func (*Site) List(keyword string, page, size int) (any, error) {

	var list []entity.Site

	db := data.GetDb().Model(&entity.Site{})
	if keyword != "" {
		db = db.Where("name like ?", keyword)
	}

	//查询总条数
	var total int64 = 0
	err := db.Count(&total).Error
	if err != nil {
		return nil, err
	}

	//分页
	db = db.Limit(size)
	db = db.Offset((page - 1) * size)

	//查询数据
	err = db.Find(&list).Error
	if err != nil {
		return nil, err
	}

	//封装数据返回
	result := map[string]any{
		"page":   page,
		"size":   size,
		"record": list,
		"total":  total,
	}

	return result, nil
}
